﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO.Compression;
using System.Threading;
using System.Diagnostics;
using System.Xml;
using System.Net;
using System.IO;
using System.Reflection;
using System.Text.RegularExpressions;

namespace Update
{
    public partial class Form1 : Form
    {
        private SynchronizationContext mContext;
        string downloadUrl;


        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //try
            //{
                /*Assembly assembly = Assembly.ReflectionOnlyLoadFrom(Application.StartupPath+"/"+"WinHBM.exe");
                string[] assemblyInfo = Regex.Split(assembly.FullName, ",", RegexOptions.IgnoreCase);
                string[] versionInfo = Regex.Split(assemblyInfo[1], "=", RegexOptions.IgnoreCase);
                this.labVersion.Text = versionInfo[1];*/
                
            //}
            //catch (Exception e1)
            //{
             //   MessageBox.Show(e1.Message);
              //  throw;
            //}


            downloadUrl = GetDownloadUrl();
            this.mContext = SynchronizationContext.Current;
            Thread t = new Thread(new ThreadStart(Download));
            t.Start();

        }


        public String GetDownloadUrl()
        {
            WebClient wc = new WebClient();
            Stream stream = wc.OpenRead("http://hbm.jyq365.com/download/ytj/update.xml");
            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.Load(stream);
            XmlNode list = xmlDoc.SelectSingleNode("Update");
            string url = list.SelectSingleNode("Soft").SelectSingleNode("DownLoad").InnerText;
            return url;
        }


        public void Download()
        {
            Thread.Sleep(2000);
            this.mContext.Post(Download,null);
        }


        public void Download(Object state)
        {
            DownloadFile(downloadUrl, "lasted.zip", this.progress, this.labPercent);
            labTitle.Text = "正在解压...";
            System.Windows.Forms.Application.DoEvents();

            //根据zip包，删除zip内部本地已有的文件
            DeleteExistFiles();

            ZipFile.ExtractToDirectory("lasted.zip", Application.StartupPath);
            File.Delete(Application.StartupPath + "/lasted.zip");
            
            Process process = new Process();
            ProcessStartInfo startInfo = new ProcessStartInfo();
            startInfo.FileName = "WinHBM.exe";
            process.StartInfo = startInfo;
            process.Start();
            this.Close();
        }

        public void DeleteExistFiles()
        {
            ZipArchive za = new ZipArchive(new FileStream("lasted.zip", FileMode.Open));
            foreach (ZipArchiveEntry entry in za.Entries)
            {
                string name = entry.FullName;
                if (name.EndsWith("/"))
                {
                    continue;
                }
                if (File.Exists(name))
                {
                    File.Delete(name);
                }
            }
            za.Dispose();
        }

        public void DownloadFile(string URL, string filename, System.Windows.Forms.ProgressBar prog, System.Windows.Forms.Label label1)
        {
            float percent = 0;
            try
            {
                System.Net.HttpWebRequest Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL);
                System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse();
                long totalBytes = myrp.ContentLength;
                if (prog != null)
                {
                    prog.Maximum = (int)totalBytes;
                }
                System.IO.Stream st = myrp.GetResponseStream();
                System.IO.Stream so = new System.IO.FileStream(filename, System.IO.FileMode.Create);
                long totalDownloadedByte = 0;
                byte[] by = new byte[1024];
                int osize = st.Read(by, 0, (int)by.Length);
                while (osize > 0)
                {
                    totalDownloadedByte = osize + totalDownloadedByte;
                    System.Windows.Forms.Application.DoEvents();
                    so.Write(by, 0, osize);
                    if (prog != null)
                    {
                        prog.Value = (int)totalDownloadedByte;
                    }
                    osize = st.Read(by, 0, (int)by.Length);

                    percent = (float)totalDownloadedByte / (float)totalBytes * 100;
                    label1.Text = ((int)percent).ToString() + "%";
                    System.Windows.Forms.Application.DoEvents(); //必须加注这句代码，否则label1将因为循环执行太快而来不及显示信息
                }
                so.Close();
                st.Close();
            }
            catch (System.Exception e)
            {
                MessageBox.Show(e.Message);
                throw;
            }
        }
        

        private void Form1_Activated(object sender, EventArgs e)
        {

            
        }
    }
}
